package servlet;

import com.alibaba.fastjson.JSON;
import pojo.Admin;
import service.IAdminService;
import service.impl.AdminServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(value = "/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        // 得到提交的验证码 2040706301 -雷诏华
        String code = request.getParameter("code");
        // 获取session中的验证码
        Object randStr = request.getSession().getAttribute("randStr");
        // 判断用户输入的验证码是否正确，若不正确，则页面重定向到login.jsp页面
        if (!code.equals(randStr)){
            response.getWriter().append(JSON.toJSONString("验证码错误"));
            return;
        }
        //否则执行下面的操作
        IAdminService adminService=new AdminServiceImpl();
        Admin admin=new Admin();
        admin.setAccount(request.getParameter("account"));
        admin.setPassword(request.getParameter("password"));
        Admin result;
        try {
            result = adminService.login(admin);
            if (result!=null) {
                request.getSession().setAttribute("user", admin);
                response.getWriter().append(JSON.toJSONString("success"));
                //response.sendRedirect("showAllBooksServlet");
            }else {
                response.getWriter().append(JSON.toJSONString("账号或者密码错误"));
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
